<template>
	<view class="all-function">
		<scroll-view class="scroll-view_H" scroll-y="true">
			<!-- <view class="common-fun p-b-20">
				<view class="common-fun-title">
					<view class="custom-title flex align-center">
						<view class="dot"></view>
						<text class="f-bold color-323232 f-s-32">常用功能</text>
					</view>
				</view>

				<dragAndDropSort :list="list" :props="props" @change="onDragSortChange"></dragAndDropSort>
			</view> -->
			<view class="common-fun m-t-15 p-b-20">
				<view class="common-fun-title">
					<view class="custom-title flex align-center">
						<view class="dot"></view>
						<text class="f-bold color-323232 f-s-32">常用功能</text>
					</view>
				</view>
				<view class="content flex flex-wrap">
					<view class="item" v-for="(item,index) in regularMenuList" :key="index">
						<view v-if="item.skipType == '4'" style="width: 100%;height: 100%;position: relative;">
							<view class="flex flex-column align-center p-t-10 p-b-10"
								@click="clickMenuReduce(item,index)">
								<img v-if="item.isIndex != '1' && !isShow" class="add-ico"
									src="@/static/images/homeIndex/menu-reduce-ico.png" alt="">
								<view class="ico-shadow">
									<img style="width: 60rpx;height: 60rpx;"
										:src="require('@/static/svg/'+item.icon+'.svg')" alt="">
								</view>
								<text class="p-t-10 p-b-10"
									:style="[{'fontWeight':(item.isBold=='1'?'bold':'normal')},{'fontSize':item.fontSize+'rpx'},{'color':item.fontColour}]">{{item.name}}</text>
							</view>
							<wx-open-launch-weapp v-if="isShow" :appid="item.reserve"
								:path="decodeURIComponent(item.skipAddress) || '/'"
								style="position: absolute;left: 0;top: 0;width: 100%;height: 100%; opacity:0;z-index: 9999;-webkit-tap-highlight-color:transparent !important;">
								<script type="text/wxtag-template">
									<button style="position: absolute;left: 0;top: 0;width: 100%;height:100%;opacity:0;z-index: 9999;-webkit-tap-highlight-color:transparent !important;"></button>
								</script>
							</wx-open-launch-weapp>
						</view>
						<view v-else class="flex flex-column align-center p-t-10 p-b-10"
							@click="clickMenuReduce(item,index)">
							<img v-if="item.isIndex != '1' && !isShow" class="add-ico"
								src="@/static/images/homeIndex/menu-reduce-ico.png" alt="">
							<view class="ico-shadow" @click="jumpDetail(item)">
								<img style="width: 60rpx;height: 60rpx;"
									:src="require('@/static/svg/'+item.icon+'.svg')" alt="">
							</view>
							<text class="p-t-10 p-b-10"
								:style="[{'fontWeight':(item.isBold=='1'?'bold':'normal')},{'fontSize':item.fontSize +'rpx'},{'color':item.fontColour}]">{{item.name}}</text>

						</view>


					</view>
					<view v-if="isShow" class="item flex flex-column align-center p-t-10 p-b-10" @click="editMenu">
						<div class="ico-shadow"
							style="border: 1px dashed #36D092;background-color: rgba(54, 208, 146, 0.1)">
							<img style="width: 56rpx;" src="@/static/images/homeIndex/edit-ico.png" alt="">
						</div>
						<text class="p-t-10 p-b-10" style="font-size: 28rpx;font-weight: bold;">编辑</text>
					</view>
					<view v-else class="item flex flex-column align-center p-t-10 p-b-10" @click="saveMenu">
						<div class="ico-shadow" style="background-color: rgba(54, 208, 146, 0.1)">
							<img style="width: 60rpx;" src="@/static/images/homeIndex/save-ico.png" alt="">
						</div>
						<text class="p-t-10 p-b-10" style="font-size: 28rpx;font-weight: bold;">保存</text>
					</view>
				</view>
			</view>

			<view class="common-fun m-t-15 p-b-20" v-for="(item,index) in functionList" :key="index">
				<view class="common-fun-title">
					<view class="custom-title flex align-center">
						<view class="dot"></view>
						<text class="f-bold color-323232 f-s-32">{{item.parentName}}</text>
					</view>
				</view>
				<view class="content flex flex-wrap">
					<view class="item" v-for="a in item.menuList" :key="a.menuCode">
						<view v-if="a.skipType == '4'" style="width: 100%;height: 100%;position: relative;">
							<view class="flex flex-column align-center p-t-10 p-b-10" @click="clickMenuAdd(a)">
								<img v-if="a.isIndex != '1' && !isShow && noSelect(a.menuCode)" class="add-ico"
									src="@/static/images/homeIndex/menu-add-ico.png" alt="">
								<view class="ico-shadow">
									<img style="width: 60rpx;height: 60rpx;"
										:src="require('@/static/svg/'+a.icon+'.svg')" alt="">
								</view>
								<text class="p-t-10 p-b-10"
									:style="[{'fontWeight':(a.isBold=='1'?'bold':'normal')},{'fontSize':a.fontSize+'rpx'},{'color':a.fontColour}]">{{a.name}}</text>
							</view>
							<wx-open-launch-weapp v-if="isShow" :appid="a.reserve"
								:path="decodeURIComponent(a.skipAddress) || '/'"
								style="position: absolute;left: 0;top: 0;width: 100%;height: 100%; opacity:0;z-index: 9999;-webkit-tap-highlight-color:transparent !important;">
								<script type="text/wxtag-template">
									<button style="position: absolute;left: 0;top: 0;width: 100%;height:100%;opacity:0;z-index: 9999;-webkit-tap-highlight-color:transparent !important;"></button>
								</script>
							</wx-open-launch-weapp>
						</view>
						<view v-else class="flex flex-column align-center p-t-10 p-b-10" @click="clickMenuAdd(a)">
							<img v-if="a.isIndex != '1' && !isShow && noSelect(a.menuCode)" class="add-ico"
								src="@/static/images/homeIndex/menu-add-ico.png" alt="">
							<view class="ico-shadow" @click="jumpDetail(a)">
								<img style="width: 60rpx;height: 60rpx;" :src="require('@/static/svg/'+a.icon+'.svg')"
									alt="">
							</view>
							<text class="p-t-10 p-b-10"
								:style="[{'fontWeight':(a.isBold=='1'?'bold':'normal')},{'fontSize':a.fontSize+'rpx'},{'color':a.fontColour}]">{{a.name}}</text>
						</view>
					</view>
				</view>

			</view>

		</scroll-view>

		<!-- 挂号须知 -->
		<u-popup :show="registerKnowe" :customStyle="{'width':'90%'}" :round="10" :safeAreaInsetBottom="true"
			mode="center">
			<view class="top-bar flex align-center justify-center p-t-20 p-b-20">
				<text class="color-323232 f-s-36 f-bold">挂号须知</text>
			</view>
			<view class="ercode-pop flex flex-column p-b-20">
				<scroll-view style="width: 100%;height: 60vh;padding-bottom: 20rpx;" scroll-y="true">
					<text
						style="font-size: 28rpx;line-height: 40rpx; color: #323232;letter-spacing: 3px;">{{registerKnownContent}}</text>
				</scroll-view>
				<u-button type="primary" style="width:90%;" @click.native="readDone">已阅读</u-button>
			</view>
		</u-popup>

		<!-- loading -->
		<u-overlay :show="loading" :opacity="0.8">
			<view class="warp">
				<view class="rect" @tap.stop>
					<view class="lds-ripple">
						<view></view>
						<view></view>
					</view>
				</view>
			</view>
		</u-overlay>
	</view>
</template>
<script>
	import {
		getAllmenuFunction,
		configMenuSave,
		getConfigMenuList,
		configMenuDel,
		jumpToProgram,
		getConfigKey
	} from "@/api/home/home.js";
	import {
		getDictType
	} from "@/api/system/public.js";
	import dragAndDropSort from '@/components/drag-sorts/index.vue';
	import wx from 'weixin-js-sdk';
	import {
		arrNoRepeat
	} from "@/utils/common.js";
	import aes from "@/utils/Encryption.js";
	import {
		getInpatientInfo
	} from "@/api/beInHospital/index.js"
	import {
		EventBus
	} from "@/utils/event-bus.js";
	export default {
		components: {
			dragAndDropSort,
		},
		data() {
			return {
				loading: false,
				registerKnowe: false,
				props: {
					label: 'label'
				},
				// 这个内容可以自定义
				list: [{
					url: require('@/static/images/homeIndex/function-ico.png'),
					label: '啊实实'
				}],
				menuClassifyTrans: {},
				regularMenuList: [],
				functionList: [],
				isShow: true,
				hospitalCode: '',
				jumpTypeCode: '1',
				registerKnownContent: '',
			}
		},
		onLoad: function() {
			this.getConfig()
			this.initConfig()
			let hospital = uni.getStorageSync('hospital')
			this.hospitalCode = JSON.parse(hospital).hospitalCode
			this.getDict()
		},
		methods: {
			/* 获取参数配置 */
			getConfig() {
				getConfigKey('register_known').then(res => {
					console.log(res)
					this.registerKnownContent = res.msg
				});
			},
			/* 注册小程序标签 */
			initConfig() {
				var params = {
					//不需要后面的hash值
					//服务器计算签名的时候需要用到当前网页的链接，且链接里不需要hash值，所以做这个处理
					url: window.location.href
				}
				jumpToProgram(params).then(res => {
					console.log(res)
					var a = res.data;
					wx.config({
						debug: false,
						appId: a.appId,
						timestamp: a.timestamp,
						nonceStr: a.nonceStr,
						signature: a.signature,
						jsApiList: ['onMenuShareTimeline'],
						openTagList: ['wx-open-launch-weapp']
					})
					wx.ready(() => {
						//这里是成功后执行
						// alert('成功')
					});
					wx.error(() => {
						//这里是出现异常执行
						// alert('失败')
					})
				});

			},
			/* 增加菜单 */
			clickMenuAdd(res) {
				if (this.regularMenuList.find(item => item.menuCode == res.menuCode) != undefined) {
					return
				}
				if (res.isIndex != '1' && !this.isShow || this.noSelect(res.menuCode) && !this.isShow) {

					// if (this.regularMenuList.length + 1 == 8) {
					// 	this.$msg("首页区块最多添加7个应用")
					// 	return
					// }
					this.regularMenuList.push(res)
				}
			},
			/* 减菜单 */
			clickMenuReduce(res, index) {
				if (res.isIndex == '1') {
					return
				}
				if (res.isIndex != '1' && !this.isShow || this.noSelect(res.menuCode) && !this.isShow) {
					this.regularMenuList.splice(index, 1)
				}
			},
			jumpDetail(res) {
				console.log('详情====',res)
				/* 跳转详情 */
				if (this.isShow) {
					/* skipType:1路由详情，2路由列表，3第三方url，4小程序 */
					if (res.skipType == '1') {
						uni.navigateTo({
							url: '/pages/home/menuDetail?id=' + res.id + '&menuCode=' + res.menuCode +
								'&menuName=' + res.name
						})
					}
					if (res.skipType == '2') {
						uni.navigateTo({
							url: '/pages/home/menuList?id=' + res.id + '&menuCode=' + res.menuCode + '&menuName=' +
								res.name
						})
					}
					if (res.skipType == '3') {
						if (decodeURIComponent(res.skipAddress).includes('{name}') || decodeURIComponent(res.skipAddress)
							.includes('{idNum}') || decodeURIComponent(res.skipAddress).includes('{cardNum}') ||
							decodeURIComponent(res.skipAddress).includes('{HospitalCode}') || decodeURIComponent(res
								.skipAddress).includes('{openid}')) {
							if (uni.getStorageSync('currentVisitCard') == '') {
								this.$tab.navigateTo('/pages/addHealthCard/index')
							} else {
								let str = decodeURIComponent(res.skipAddress)
								let username = JSON.parse(uni.getStorageSync('currentVisitCard')).name || ''
								let useridNum = JSON.parse(uni.getStorageSync('currentVisitCard')).idNum || ''
								let usercardNum = JSON.parse(uni.getStorageSync('currentVisitCard')).cardNum || ''
								let hospitalCode = JSON.parse(uni.getStorageSync('hospital')).hospitalCode || ''
								let openid = uni.getStorageSync('openid') || ''
								let resultUrl = str.replace('{name}', username).replace('{idNum}', useridNum)
									.replace('{cardNum}', usercardNum).replace('{HospitalCode}', hospitalCode).replace(
										'{openid}', openid);
								console.log(resultUrl, '------满意度调查-------------')
								// uni.navigateTo({
								// 	url: '/pages/home/webview?url=' + resultUrl + '&title=' +
								// 		res.name
								// })
								window.location.href = resultUrl
							}
						} else {
							// uni.navigateTo({
							// 	url: '/pages/home/webview?url=' + decodeURIComponent(res.skipAddress) + '&title=' + res.name
							// })

							if (decodeURIComponent(res.skipAddress).includes('{patentid}')) { //参数AES加密
								if (uni.getStorageSync('currentVisitCard') == '') {
									this.$tab.navigateTo('/pages/addHealthCard/index')
								} else {
									let str = decodeURIComponent(res.skipAddress)
									let usercardNum = JSON.parse(uni.getStorageSync('currentVisitCard')).cardNum || ''
									let resultUrl = str.replace('{patentid}', aes.encrypt(usercardNum));
									console.log(resultUrl, '------AES加密-------------')
									window.location.href = decodeURIComponent(resultUrl)
								}

							} else {
								window.location.href = decodeURIComponent(res.skipAddress)
							}
						}
					}
					if (res.skipType == '5') {
						if (res.name == '预约挂号' || res.name == '当班挂号') {
							if (uni.getStorageSync('currentVisitCard') == '') {
								this.$tab.navigateTo('/pages/addHealthCard/index')
							} else {
								this.registerKnowe = true
								this.jumpTypeCode = res.name == '预约挂号' ? '1' : '2'
							}
						} else {
							if (res.name == '门诊缴费' || res.name == '押金缴纳' || res.name == '一日清单' || res.name == '挂号记录' || res
								.name == '押金记录') {
								if (uni.getStorageSync('currentVisitCard') == '') {
									this.$tab.navigateTo('/pages/addHealthCard/index')
								} else {
									let params = {
										name: JSON.parse(uni.getStorageSync('currentVisitCard')).name || '',
										idNum: JSON.parse(uni.getStorageSync('currentVisitCard')).idNum || ''
									}
									if (res.name == '押金缴纳' || res.name == '一日清单' || res.name == '押金记录') {
										getInpatientInfo(params).then(result => {
											uni.navigateTo({
												url: decodeURIComponent(res.skipAddress)
											})
										}).catch(errors => {
											if(errors == '没有找到住院信息！' && res.name == '押金缴纳'){
												uni.navigateTo({
													url: '/pages/home/inHos'
												})
											}
										});
									} else {
										uni.navigateTo({
											url: decodeURIComponent(res.skipAddress)
										})
									}
								}
							} else {
								console.log('6666666666666666666')
								uni.navigateTo({
									url: decodeURIComponent(res.skipAddress)
								})
							}
						}

					}
				}
			},
			readDone() {
				this.registerKnowe = false
				if (this.jumpTypeCode == '1') {
					uni.navigateTo({
						url: '/pages/mine/selectDepartment/index?registerType=1'
					})
				}
				if (this.jumpTypeCode == '2') {
					uni.navigateTo({
						url: '/pages/mine/selectDepartment/index?registerType=2'
					})
				}
			},
			noSelect(code) {
				if (this.regularMenuList.find(item => item.menuCode == code) == undefined) {
					return true
				} else {
					return false
				}
			},
			editMenu() {
				this.isShow = false
			},
			saveMenu() {
				this.isShow = true
				let newMenu = this.regularMenuList.filter(item => item.isIndex != '1')
				if (newMenu.length == 0) {
					this.$msg("保存成功！")
					EventBus.$emit('loadFunction', '')
				} else {
					let openid = uni.getStorageSync('openid') || ''
					let params = newMenu.map(item => {
						return {
							hospitalCode: this.hospitalCode,
							openId: openid,
							menuId: item.id,
							menuCode: item.menuCode,
						}
					})

					/* 保存菜单 */
					configMenuSave(params).then(res => {
						this.$msg("保存成功！")
						EventBus.$emit('loadFunction', '')
					});
				}


			},
			/* 获取所有功能菜单列表 */
			getFunctionList() {
				getAllmenuFunction().then(res => {
					console.log(res)
					this.loading = false
					this.initData(res.rows)
				});
			},
			/* 获取自定义菜单 */
			getMenuList(data, regularMenu) {
				let openid = uni.getStorageSync('openid') || ''
				getConfigMenuList({
					openId: openid
				}).then(res => {
					let results = []
					res.rows.forEach(item => {
						for (let i in data) {
							if (item.menuCode == data[i].menuCode) {
								results.push(data[i])
							}
						}
					})
					this.regularMenuList = regularMenu.concat(results).filter(item => item.valid == '1') //返回有效菜单
					this.regularMenuList = arrNoRepeat(this.regularMenuList, 'menuCode')
				});
			},
			initData(data = []) {
				/* 固定功能 */
				let regularMenu = []
				for (let i in data) {
					if (data[i].isIndex == '1') {
						regularMenu.push(data[i])
					}
				}
				this.getMenuList(data, regularMenu)


				/* 大类code */
				let parentCode = []
				for (let i in data) {
					parentCode.push(data[i].menuType)
				}
				let a = Array.from(new Set(parentCode))
				/* 大类name */
				let parent = []
				for (let i in a) {
					parent.push({
						parentCode: a[i],
						parentName: this.menuClassifyTrans[a[i]],
						menuList: []
					})
				}
				for (let i in parent) {
					for (let k in data) {
						if (parent[i].parentCode == data[k].menuType && data[k].valid == '1') {
							parent[i].menuList.push(data[k])
						}
					}
				}
				this.functionList = parent
			},
			/* 字典 */
			getDict() {
				this.loading = true
				getDictType({
					dictType: 'menu_classify'
				}).then(res => {
					if (res.code == 200) {
						res.rows.forEach(item => {
							this.menuClassifyTrans[item.dictValue] = item.dictLabel
						})
					}
					this.getFunctionList()
				});
			},
			onDragSortChange(e) {}
		}
	}
</script>

<style scoped lang="scss">
	page {
		height: 100%;

		.fontWeight {
			font-weight: bold;
		}

		.ercode-pop {
			width: 90%;
			margin-left: 5%;

			.avatar {
				width: 160rpx;
			}

			.ercode {
				width: 100%;
			}
		}

		.all-function {
			width: 100%;
			height: 100%;
			background-color: #F6F7F9;

			.ico-shadow {
				padding: 20rpx;
				border-radius: 35rpx;
				background: rgba(77, 142, 255, 0.1);

				img {
					display: block;
				}
			}

			.scroll-view_H {
				width: 100%;
				height: 100%;

				.common-fun {
					background-color: #fff;

					.common-fun-title {
						padding: 30rpx 30rpx 10rpx 30rpx;

					}

					.content {
						width: 94%;
						margin-left: 3%;

						.item {
							width: 25%;
							position: relative;

							text {
								color: #323232;
							}

							.add-ico {
								width: 30rpx;
								height: 30rpx;
								position: absolute;
								right: 30rpx;
								top: 0;
							}
						}
					}


				}




			}

			.custom-title {
				.dot {
					width: 10rpx;
					height: 32rpx;
					border-radius: 10rpx;
					background-color: #4D8EFF;
					margin-right: 10rpx;
				}
			}

		}

	}
</style>